Pytest Setup

Part 1, Chapter 6


Let's get our tests up and running for this endpoint with pytest.


Setup

Add a "tests" directory to the "project" directory, and then create the following files inside the newly created directory:

  1. __init__.py
  2. conftest.py
  3. test_ping.py

By default, pytest will auto-discover test files that start or end with test -- e.g., test_*.py or *_test.py. Test functions must begin with test_, and if you want to use classes they must also begin with Test.

Example:

# if a class is used, it must begin with Test
class TestFoo:

    # test functions must begin with test_
    def test_bar(self):
        assert "foo" != "bar"

If this is your first time with pytest be sure to review the Installation and Getting Started guide.

Fixtures

Define a test_app fixture in conftest.py:

# project/tests/conftest.py


import os

import pytest
from starlette.testclient import TestClient

from app import main
from app.config import get_settings, Settings


def get_settings_override():
    return Settings(testing=1, database_url=os.environ.get("DATABASE_TEST_URL"))


@pytest.fixture(scope="module")
def test_app():
    # set up
    main.app.dependency_overrides[get_settings] = get_settings_override
    with TestClient(main.app) as test_client:

        # testing
        yield test_client

    # tear down

Here, we imported Starlette's TestClient, which uses the Requests library to make requests against the FastAPI app.

To override the dependencies, we used the dependency_overrides attribute:

main.app.dependency_overrides[get_settings] = get_settings_override

dependency_overrides is a dict of key/value pairs where the key is the dependency name and the value is what we'd like to override it with:

  • key: get_settings
  • value: get_settings_override

Fixtures are reusable objects for tests. They have a scope associated with them, which indicates how often the fixture is invoked:

  1. function - once per test function (default)
  2. class - once per test class
  3. module - once per test module
  4. session - once per test session

Check out All You Need to Know to Start Using Fixtures in Your pytest Code for more on pytest fixtures.

Take note of the test_app fixture. In essence, all code before the yield statement serves as setup code while everything after serves as the teardown.

For more on this review Fixture finalization / executing teardown code.

Then, add pytest and Requests to the requirements file:

pytest==6.2.5
requests==2.26.0

We need to re-build the Docker images since requirements are installed at build time rather than run time:

$ docker-compose up -d --build

With the containers up and running, run the tests:

$ docker-compose exec web python -m pytest

You should see:

=============================== test session starts ===============================
platform linux -- Python 3.10.1, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /usr/src/app
plugins: anyio-3.4.0
collected 0 items

============================== no tests ran in 0.07s ==============================

Tests

Moving on, let's add a quick test to test_ping.py:

# project/tests/test_ping.py


from app import main


def test_ping(test_app):
    response = test_app.get("/ping")
    assert response.status_code == 200
    assert response.json() == {"environment": "dev", "ping": "pong!", "testing": True}

While unittest requires test classes, pytest just requires functions to get up and running. In other words, pytest tests are just functions that either start or end with test.

You can still use classes to organize tests in pytest if that's your preferred pattern.

To use the fixture, we passed it in as an argument.

Run the tests again:

$ docker-compose exec web python -m pytest

You should see:

=============================== test session starts ===============================
platform linux -- Python 3.10.1, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /usr/src/app
plugins: anyio-3.4.0
collected 1 item

tests/test_ping.py .                                                        [100%]

================================ 1 passed in 0.13s ================================

Given-When-Then

When writing tests, try to follow the Given-When-Then framework to help make the process of writing tests easier and faster. It also helps communicate the purpose of your tests better so it should be easier to read by your future self and others.

State Explanation Code
Given the state of the application before the test runs setup code, fixtures, database state
When the behavior/logic being tested code under test
Then the expected changes based on the behavior asserts

Example:

def test_ping(test_app):
    # Given
    # test_app

    # When
    response = test_app.get("/ping")

    # Then
    assert response.status_code == 200
    assert response.json() == {"environment": "dev", "ping": "pong!", "testing": True}



✓ Mark as Completed